<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:lbm:add']"
          >新增</el-button
        >
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAssign"-->
      <!--          v-hasPermi="['project:lbm:assign']"-->
      <!--        >分配仓位-->
      <!--        </el-button>-->
      <!--      </el-col>-->

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <u-table
      ref="table"
      v-loading="loading"
      use-virtual
      showBodyOverflow="title"
      showHeaderOverflow="title"
      row-id="lbmId"
      :row-height="24"
      :data="lbmList"
      :class="$style.lbmlist"
      row-key="lbmId"
      :height="height"
      border
      stripe
      highlight-current-row
      :row-style="{ padding: '0px' }"
      :header-row-style="{ padding: '2px' }"
      :header-cell-style="{ 'text-align': 'center', padding: '2px' }"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <u-table-column width="105">
        <template #default="scope">
          <el-checkbox
            v-if="
              (scope.row.lbmType !== '205' && scope.row.children != null) ||
              scope.row.lbmType === '204'
            "
            v-model="scope.row.checks"
            style="padding-left: 10px"
            @change="checkChange(scope.row)"
          />
        </template>
      </u-table-column>
      <u-table-column
        label="类别代码"
        width="80"
        prop="lbmLbdm"
        class-name="lbdm"
        :tree-node="true"
      ></u-table-column>
      <u-table-column
        label="类别名称"
        show-overflow-tooltip
        min-width="180"
        align="center"
        prop="lbmLbmc"
      />
      <u-table-column
        label="类别类型"
        width="80"
        align="center"
        prop="lbmType"
      />
      <!--      <u-table-column label="仓位分配" width="80" show-overflow-tooltip align="center" prop="storageName"/>-->
      <u-table-column
        label="描述"
        width="80"
        show-overflow-tooltip
        align="center"
        prop="remark"
      />
      <u-table-column label="有效标志" width="80" align="center" prop="lbmFlag">
        <template #default="scope">
          <dict-tag :options="lbmFlagOptions" :value="scope.row.lbmFlag" />
        </template>
      </u-table-column>
      <u-table-column
        label="创建人员"
        width="80"
        align="center"
        prop="createBy"
      />
      <u-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </u-table-column>
      <u-table-column
        label="更新人员"
        width="80"
        align="center"
        prop="updateBy"
      />
      <u-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="150"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, "{y}-{m}-{d}") }}</span>
        </template>
      </u-table-column>
      <u-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:lbm:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['project:lbm:add']"
            v-if="scope.row.lbmType !== '205'"
          >
            新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:lbm:remove']"
          >
            删除
          </el-button>
        </template>
      </u-table-column>
    </u-table>

    <!-- 添加或修改类别代码对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      :close-on-click-modal="false"
      draggable
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item
          v-if="this.title === '添加类别代码'"
          label="类别代码"
          prop="lbmLbdm"
        >
          <el-input v-model="form.lbmLbdm" placeholder="请输入类别代码" />
        </el-form-item>
        <el-form-item label="类别名称" prop="lbmLbmc">
          <el-input v-model="form.lbmLbmc" placeholder="请输入类别名称" />
        </el-form-item>
        <!--        <el-form-item label="类别类型" prop="lbmType">
                  <el-input v-model="form.lbmType" placeholder="请输入类别类型" />
                </el-form-item>-->

        <!--        <el-form-item label="类别类型">
                  <el-radio-group v-model="form.lbmType">
                    <el-radio
                      v-for="dict in lbmTypeOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue"
                    >{{dict.dictLabel}}</el-radio>
                  </el-radio-group>
                </el-form-item>-->

        <el-form-item label="有效标志">
          <el-radio-group v-model="form.lbmFlag">
            <el-radio
              v-for="dict in lbmFlagOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              >{{ dict.dictLabel }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <!--        加提示，如果当前为中分类添加子类的话，提示它如果有其他相同的中分类，则会同时添加  -->

        <el-form-item label="父项ID" prop="lbmParentId">
          <treeselect
            v-model="form.lbmParentId"
            :options="lbmOptions"
            :normalizer="normalizer"
            placeholder="请选择父项ID"
            disabled
          />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="650px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="12">
          <el-form-item label="类别代码" prop="lbmLbdm">
            <el-input
              v-model="queryParams.lbmLbdm"
              placeholder="请输入类别代码"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类别名称" prop="lbmLbmc">
            <el-input
              v-model="queryParams.lbmLbmc"
              placeholder="请输入类别名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类别类型" prop="lbmType">
            <el-input
              v-model="queryParams.lbmType"
              placeholder="请输入类别类型"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效标志" prop="lbmFlag">
            <el-select
              v-model="queryParams.lbmFlag"
              placeholder="请选择有效标志"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in lbmFlagOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <!--分配仓位弹窗-->
    <el-dialog
      :title="title"
      v-model="openSt"
      :close-on-click-modal="false"
      draggable
      width="800px"
      append-to-body
    >
      <el-form
        :model="queryStore"
        ref="queryFormstr"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="仓库代码" prop="storageCode">
          <el-input
            v-model="queryStore.storageCode"
            placeholder="请输入仓库代码"
            clearable
            size="small"
            @keyup.enter.native="handleQueryStr"
          />
        </el-form-item>
        <el-form-item label="仓位名称" prop="storageName">
          <el-input
            v-model="queryStore.storageName"
            placeholder="请输入仓位名称"
            clearable
            size="small"
            @keyup.enter.native="handleQueryStr"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQueryStr"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryStr"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="StorageList"
        @current-change="clickChange"
        ref="Table"
      >
        <el-table-column label="选择" width="55">
          <template #default="scope">
            <el-radio v-model="tableRadio" :label="scope.row"><i></i></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="仓库代码" align="center" prop="storageCode" />
        <el-table-column label="仓位名称" align="center" prop="storageName" />
        <el-table-column
          label="默认储位代码"
          align="center"
          prop="storageDefaultstorage"
        />
      </el-table>
      <pagination
        v-if="totalSearch > 0"
        :total="totalSearch"
        :page.sync="queryStore.pageNum"
        :limit.sync="queryStore.pageSize"
        @pagination="getListStr"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSt">取 消</el-button>
        <el-button type="primary" @click="submitStorageForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--    <le-dialog>-->

    <!--    </le-dialog>-->
  </div>
</template>

<script>
import {
  listLbm,
  getLbm,
  delLbm,
  addLbm,
  updateLbm,
  exportLbm,
  batchAdd,
  batchDelete,
  batchUpdateLbm,
  getAreaTree,
  bindStorageForLbm,
} from "@/api/project/lbm";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import log from "../../monitor/job/log";
import { listStorage } from "@/api/repertory/Storage";

export default {
  name: "Lbm",
  components: {
    Treeselect,
  },
  data() {
    return {
      height: document.body.clientHeight - 200,
      totalSearch: 0,
      //选中的数据
      chooseData: [],
      StorageList: [],
      uploadData: {},
      lbmLbdmList: [],
      lbmIds: [],
      ids: null,
      storageId: null,
      tableRadio: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      //批量
      batchFlag: false,
      // 选中
      checkouts: true,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 类别代码表格数据
      lbmList: [],
      // 类别代码树选项
      lbmOptions: [],

      multipleSelection: null,

      //所有树状数据
      lbmData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSearch: false,

      openSt: false,
      // 有效标志字典
      lbmFlagOptions: [],
      // 类型
      lbmTypeOptions: [
        {
          dictValue: "203",
          dictLabel: "大分类",
        },
        {
          dictValue: "204",
          dictLabel: "中分类",
        },
        {
          dictValue: "205",
          dictLabel: "小分类",
        },
      ],
      // 查询参数
      queryParams: {
        lbmLbdm: null,
        lbmLbmc: null,
        lbmType: null,
        lbmFlag: null,
      },

      queryStore: {
        pageNum: 1,
        pageSize: 10,
        storageCode: null,
        storageName: null,
        storageFlag: "0",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        lbmLbdm: [
          { required: true, message: "类别代码不能为空", trigger: "blur" },
        ],
        lbmLbmc: [
          { required: true, message: "类别名称不能为空", trigger: "blur" },
        ],
        lbmType: [
          { required: true, message: "类别类型不能为空", trigger: "blur" },
        ],
        lbmFlag: [
          { required: true, message: "有效标志不能为空", trigger: "blur" },
        ],
        lbmParentId: [
          { required: true, message: "父项ID不能为空", trigger: "blur" },
        ],
        createBy: [
          { required: true, message: "创建人员不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then((response) => {
      this.lbmFlagOptions = response.data;
    });
  },
  watch: {
    "form.lbmParentId": "currLbmParentId",
  },
  methods: {
    /** 选择触发事件 */

    currLbmParentId(val) {
      //拿到当前的节点ID

      //判断如果是小分类，则不允许选择

      if (val) {
        getLbm(val).then((response) => {
          if (response.data) {
            if (response.data.lbmType === "205") {
              this.msgError("小分类（三级菜单不允许添加子级菜单）");

              this.form.lbmParentId = 0;
            }
          }
        });
      }

      //去数据库中查询到前节点是否为中分类添加
    },
    /** 查询类别代码列表 */
    getList() {
      this.loading = true;
      listLbm(this.queryParams).then((response) => {
        for (let i of response.data) {
          i.checks = false;
        }
        this.lbmData = response.data;
        this.lbmList = this.handleTree(response.data, "lbmId", "lbmParentId");
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQueryStr() {
      this.queryParams.pageNum = 1;
      this.getListStr();
    },
    handleSearch() {
      this.reset();
      this.title = "查询类别代码";
      this.openSearch = true;
    },
    /** 重置按钮操作 */
    resetQueryStr() {
      this.resetForm("queryFormstr");
      this.handleQueryStr();
    },
    /** 转换类别代码数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.lbmId,
        label: node.lbmLbmc,
        children: node.children,
      };
    },
    /** 查询储位资料列表 */
    getListStr() {
      this.loading = true;
      listStorage(this.queryStore).then((response) => {
        this.StorageList = response.rows;
        this.totalSearch = response.total;
        this.loading = false;
      });
    },
    /** 查询类别代码下拉树结构 */
    getTreeselect() {
      listLbm().then((response) => {
        this.lbmOptions = [];
        const data = { lbmId: 0, lbmLbmc: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "lbmId", "lbmParentId");
        this.lbmOptions.push(data);
      });
    },
    clickChange(item) {
      if (item == null) {
        return;
      }
      this.tableRadio = item;
      this.storageId = item.storageId;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
      this.reset();
    },
    cancelSt() {
      this.openSt = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lbmId: null,
        lbmLbdm: null,
        lbmLbmc: null,
        lbmType: null,
        lbmFlag: "0",
        lbmParentId: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        batchFlag: false,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.lbmId) {
        this.form.lbmParentId = row.lbmId;
      } else {
        this.form.lbmParentId = 0;
      }

      if (row.lbmType == null) {
        this.form.lbmType = "203";
      } else {
        this.form.lbmType = (parseInt(row.lbmType) + 1).toString();

        //如果添加操作的时候父级为中分类
        if (row.lbmType === "204") {
          this.batchFlag = true;
        }
      }
      this.open = true;
      this.title = "添加类别代码";
    },
    /**分配仓位弹窗*/
    handleAssign() {
      this.lbmLbdmList = [];

      this.lbmIds = [];

      this.getLbmLbdm();

      if (this.lbmLbdmList.length === 0) {
        this.msgError("请勾选数据");

        return;
      }
      listStorage({ storageFlag: "0" }).then((response) => {
        this.StorageList = response.rows;
        this.totalSearch = response.total;
        //获取数据
        this.openSt = true;
        this.title = "分配仓位";
      });
    },

    /** 分配仓位 */
    submitStorageForm() {
      bindStorageForLbm({
        bmBmyzs: this.lbmLbdmList,
        lbmIds: this.lbmIds,
        bmStorageId: this.storageId,
      }).then((response) => {
        this.msgSuccess("分配成功");
        this.openSt = false;
        this.getList();
        for (let item of this.lbmData) {
          this.$set(item, "checks", false);
          console.log(1);
          console.log(item);
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();

      if (row != null) {
        this.form.lbmParentId = row.lbmParentId;

        if (row.lbmType === "205") {
          this.batchFlag = true;
        }
      } else {
        this.msgError("数据异常，请联系管理员");
      }
      if (row.lbmId) {
        getLbm(row.lbmId).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改类别代码";
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.batchFlag = this.batchFlag;
          if (this.form.lbmId != null) {
            updateLbm(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.batchFlag = false;
            });
          } else {
            addLbm(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.batchFlag = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      //删除操作需要将其绑定的编码原则也删除

      let bmyz = " ";

      if (row.lbmType === "204") {
        for (let item of this.lbmData) {
          if (item.lbmId === row.lbmParentId) {
            bmyz = item.lbmLbdm + "." + row.lbmLbdm;
          }
        }
      }

      if (row.lbmType === "205") {
        this.$confirm(
          '是否确认删除类别名称为"' +
            row.lbmLbmc +
            '"的数据项,同时会删除与它类别类型与类别名称相同的数据?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delLbm(row.lbmId, bmyz, true);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
            this.batchFlag = false;
          })
          .catch(() => {
            this.batchFlag = false;
          });
      } else {
        this.$confirm(
          '是否确认删除类别名称为"' + row.lbmLbmc + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delLbm(row.lbmId, bmyz, false);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(() => {});
      }
    },

    checkAllIn() {
      this.$refs.multipleTable.data.map((items) => {
        // console.log(items);
        this.$set(items, "checks", this.checkouts);
        if (items.children) {
          items.children.forEach((item) => {
            this.$set(item, "checks", this.checkouts);
          });
        }
      });
    },
    checkChange(row) {
      // 父选子

      if (row.children) {
        //正选
        // console.log(row.children)

        if (row.checks) {
          row.children.map((item) => {
            this.chooseData.push(item);
            this.$set(item, "checks", true);
            /*            if(item.children){
                          item.children.map((items =>{
                            this.$set(items, "checks", true)
                          }))
                        }*/
          });
          this.$set(row, "checks", true);
        }

        //反选
        else {
          row.children.map((item) => {
            this.$set(item, "checks", false);
            /*            if(item.children){
                          item.children.map((items =>{
                            this.$set(items, "checks", false)
                          }))
                        }*/
          });
          this.$set(row, "checks", false);
        }
      }

      // 子带父
      if (row.lbmType !== "203" && row.checks) {
        //第一步 遍历一级
        // console.log(this.lbmData)
        this.lbmData.map((items) => {
          if (row.lbmParentId === items.lbmId) {
            this.$set(items, "checks", true);
            /*            this.lbmData.map(item=>{
                          if(items.lbmParentId === item.lbmId){
                            this.$set(item, "checks", true)
                          }
                        })*/
          }
        });
        return;
      }

      // 子空父空

      const son = [];
      if (!row.checks && row.lbmParentId !== 0) {
        this.lbmData.map((ite) => {
          if (ite.children) {
            ite.children.map((items) => {
              if (items.lbmParentId === row.lbmParentId && items.checks) {
                son.push(items);
              }
            });
          }
        });
      } else {
        console.log(1);
      }

      if (son.length === 0) {
        this.lbmData.map((item) => {
          if (item.lbmId === row.lbmParentId) {
            this.$set(item, "checks", false);
            /*            this.lbmData.map(i=>{
                          if (item.lbmParentId === i.lbmId){
                            this.$set(i, "checks", false)
                          }
                        })*/
          }
        });
      }
    },

    getLbmLbdm() {
      //遍历所有数据
      for (let item of this.lbmData) {
        //第一层为203，如果有选中
        if (item.lbmType === "203" && item.checks) {
          //如果第一层有孩子节点
          if (item.children) {
            //遍历第二层节点
            for (let ite of item.children) {
              //如果第二层有选中
              if (ite.checks) {
                this.lbmIds.push(ite.lbmId);
                //判断它是否有孩子节点
                /*                if(ite.children && ite.checks){

                                  for(let it of ite.children){

                                    if(it.checks){

                                      let wldm = item.lbmLbdm +'.'+ite.lbmLbdm+'.'+it.lbmLbdm;

                                      this.lbmLbdmList.push(wldm);

                                    }

                                  }

                                }*/

                let wldm = item.lbmLbdm + "." + ite.lbmLbdm;

                this.lbmLbdmList.push(wldm);
              }
            }
          } else {
            this.lbmIds.push(item.lbmId);

            let wldm = item.lbmLbdm;

            this.lbmLbdmList.push(wldm);
          }
        }
      }
    },
  },
};
</script>
<style module lang="scss">
.el-table .cell {
  white-space: normal;
}
.lbmlist {
  :global(.el-table__row--level-1 .lbdm) {
    padding-left: 15px !important;
  }
  :global(.el-table__row--level-2 .lbdm) {
    padding-left: 30px !important;
  }
}
</style>
